<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\ProjectRequest;
use App\Http\Resources\ProjectResource;
use App\Models\Project;
use Illuminate\Database\Eloquent\Builder;

class ProjectController extends Controller
{
    public function index(ProjectRequest $request)
    {
        $project = Project::query()->show()
            //关键词搜索
            ->when($request->get('keyword'), function (Builder $builder) use ($request) {
                $builder->where(function ($query) use ($request) {
                    $query->where('title', 'like', '%' . $request->get('keyword') . '%')
                        ->orWhere('describe', 'like', '%' . $request->get('keyword') . '%');
                });
            })
            //时间筛选
            ->when($request->get('start_date') && $request->get('end_date'), function (Builder $builder) use ($request) {
                $builder->whereBetween('date', [$request->get('start_date'), $request->get('end_date')]);
            })
            //类型筛选
            ->when($request->get('category_id'), function (Builder $builder) use ($request) {
                $builder->where('category_id', $request->get('category_id'));
            })
            //省
            ->when($request->get('province_id'), function (Builder $builder) use ($request) {
                $builder->where('province_id', $request->get('province_id'));
            })
            //市
            ->when($request->get('city_id'), function (Builder $builder) use ($request) {
                $builder->where('city_id', $request->get('city_id'));
            })
            //区
//            ->when($request->get('district_id'), function (Builder $builder) use ($request) {
//                $builder->where('district_id', $request->get('district_id'));
//            })
            ->orderBy('sort')
            ->orderBy('date')
            ->orderByDesc('id')
            ->paginate($request->get('limit', 10));
        return successReturn([
            'list' => ProjectResource::collection($project),
            'total' => $project->total(),
            'last_page' => $project->lastPage()
        ]);
    }


    //详情
    public function show(int $id)
    {
        $project = Project::query()->show()->where('id', $id)->first();
        return $project ? successReturn(new ProjectResource($project)) : successReturn();
    }
}
